package org.lifeaddict.sybill;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

class GetMuOnlineData extends AsyncTask<String, Void, MUlogin> {

		private Exception exception;
        private Context context;
        
        
        public GetMuOnlineData(Context context){
            this.context=context;
        }

        @Override
        protected MUlogin doInBackground(String... credentials) {
        	System.out.println(credentials[0]);
        	MUlogin login = null;
            try {
            	login = new MUlogin(credentials[0],credentials[1]);
            	login.setContext(context);
            	login.runLogin();
            	ArrayList<LvEvent> events = login.getEvents();
            	ArrayList<LvEventDate> dates = null;
            	ArrayList<LvEventDate> dbdates = new ArrayList<LvEventDate>();
            	DataSource ds = new DataSource(context);
            	ds.open();
            	Date now = Calendar.getInstance().getTime();
            	for(LvEvent e : events) {
            		dates = e.getDates();
            		for(LvEventDate d : dates) {
            			if (d.getDateReal().after(now)) {
            				d.setName(e.getName());
            				dbdates.add(d);
            			}
            		}
            	}
            	
            	Collections.sort(dbdates);
            	
            	for (LvEventDate dbd : dbdates) {
            		System.out.println("adding " + dbd.getName());
            		ds.createDetail(dbd.getName(), dbd.getLocation(), dbd.getDay(), dbd.getDate(), dbd.getTime());
            	}
            	
            	ds.close();
            	
            	
            } catch (Exception e) {
                this.exception = e;
            }
			return login;
        }

        @Override
        protected void onPostExecute(MUlogin login) {
            // TODO: check this.exception 
        	Toast.makeText(context, "FERTIG!", Toast.LENGTH_LONG).show();
        }
     }